package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.damain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategorySerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Transactional
public class CategoryServiceImpl implements CategorySerivce {
    @Autowired
    private CategoryMapper categoryMapper;
    //查询所有
    @Override
    public List<Category> findall() {
        return categoryMapper.findall();

    }
//新增
    @Override
    public void save(Category category) {
        //设置id
        category.setId(IdUtil.getSnowflake(1,1).nextId());
//        category.setUpdateUser(1L);
//        category.setCreateUser(1L);
//        category.setUpdateTime(new Date());
//        category.setCreateTime(new Date());

        categoryMapper.save(category);

    }
//修改分类
    @Override
    public void update(Category category) {
//        category.setUpdateTime(new Date());
//        category.setUpdateUser(1L);
        categoryMapper.uodate(category);
    }
//删除
    @Override
    public ResultInfo delete(Long id) {
        //当内部有菜品，返回错误
        Integer num1=categoryMapper.categoryDishByCstegoryId(id);
        //内部分类下有菜品，无法删除
        Integer num2=categoryMapper.categorySetmealByCategoryId(id);
        if (num1 > 0){
            throw new CustomException("内部有菜品，无法删除");

        }else if (num2>0){
            throw new CustomException("内部分类有菜品，无法删除");
        }else {
            categoryMapper.delete(id);
        }
//        if (num1>0){
//             return ResultInfo.error("内部有菜品，无法删除");
//        }else if (num2>0){
//            return ResultInfo.error("内部分类有菜品，无法删除");
////        }else {
////            categoryMapper.delete(id);
//            return ResultInfo.success(null);
//        }
        return null;
    }

    @Override
    public List<Category> findByType(Integer type) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getType,type);

        return categoryMapper.selectList(wrapper);
    }
}
